package dao;

import java.util.ArrayList;

import modelo.Material;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoMaterial {
	private SessionFactory fabrica;

	public DaoMaterial()throws Exception
	{	fabrica=new Configuration().addClass(modelo.Material.class).buildSessionFactory();
		
	}
	public void cadastrar(Material m)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.save(m);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public Material consultar(Material m)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		m=(Material)sessao.get(modelo.Material.class,m.getId_mat());
		
		transacao.commit();
		sessao.flush();
		sessao.close();
		return m;
	}
	public void excluir(Material m)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.delete(m);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	public void alterar(Material m)throws Exception
	{
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		sessao.update(m);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}
	
	public ArrayList<Material> consultarTodos(){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Material");
		ArrayList<Material> materiais=(ArrayList<Material>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return materiais;
	}
	
	public ArrayList<Material> consultarTodosNome(String nome){
		Session sessao=fabrica.openSession();
		Transaction transacao=sessao.beginTransaction();
		Query q=sessao.createQuery("from modelo.Material where nome_mat like '%" + nome + "%' order by nome_mat");
		ArrayList<Material> materiais=(ArrayList<Material>)q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return materiais;
	}
	

}
